﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;

public partial class DynamicData_FieldTemplates_OrderQty_EditField : 
    System.Web.DynamicData.FieldTemplateUserControl {

    // Set quantity range limits.
    private int Min = 10;
    private int Max = 2000;
    
    protected void Page_Load(object sender, EventArgs e) {
        TextBox1.MaxLength = Column.MaxLength;
        if (Column.MaxLength < 20)
            TextBox1.Columns = Column.MaxLength;
        TextBox1.ToolTip = Column.Description;

        SetUpValidator(RequiredFieldValidator1);
        SetUpValidator(RegularExpressionValidator1);
        SetUpValidator(DynamicValidator1);
    }
    
    protected override void ExtractValues(IOrderedDictionary dictionary) {
        dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);
    }

    public override Control DataControl {
        get {
            return TextBox1;
        }
    }
  

    protected void OrderQtyValidation(object source, ServerValidateEventArgs args)
    {
        bool result = false;
        short intUnits;
        
        result = Int16.TryParse(TextBox1.Text, out intUnits);
        if (result == true) 
        {
            // Check if the input is in the allowed range.
            result = CheckRange(intUnits);
            // Return result.    
            args.IsValid = result;
        }
        else
        {
            CustomValidator1.ErrorMessage = string.Format(
                  "Value is greater than the maximum allowed integer.");
            args.IsValid = result;
        }

    }

    protected bool CheckRange(int intUnits)
    {
        bool result = true; 

        // Check if the value is in the allowed range.
        if (intUnits < Min)
        {
            CustomValidator1.ErrorMessage = string.Format(
              "Value less than minimum threshod: {0} ", Min);
            result = false;
        }
        else
            if (intUnits > Max)
            {
                CustomValidator1.ErrorMessage = string.Format(
                  "Value greater than maximum threshod: {0} ", Max);
                result = false;
            }
        return result;
    }

}
